<?php

namespace app\command;

use app\api\service\UserOrderService;
use support\spark\model\order\Order;
use support\spark\model\user\User;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface;


class SparksAutoReceive extends Command
{
    protected static $defaultName = 'sparks:autoReceive';
    protected static $defaultDescription = 'SparkShop商城自动收货';



    /**
     * @param InputInterface $input
     * @param OutputInterface $output
     * @return int
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $orderModel =  new Order();
        $orderNum = $orderModel->where('status', 4)->count('id');

        $systemConfig = getConfByType('shop_base');
        $autoReceiveDay = $systemConfig['auto_receive_time'] ?: 7;

        $limit = 1000;
        $page = 1;
        $pageSize = ceil($orderNum / $limit);

        $userModel = new User();
        $userOrderService = new UserOrderService();

        for ($i = 0; $i < $pageSize; $i++) {
            $offset = ($page - 1) * $limit;
            $orderList = $orderModel->select('id,user_id,delivery_time')->where('status', 4)->limit($offset, $limit)->get();
            $orderList=$orderList?$orderList->toArray():[];
            foreach ($orderList as $vo) {

                $overTime = date('Y-m-d H:i:s', strtotime($vo['delivery_time']) + $autoReceiveDay * 86400);
                if ($overTime < now()) {
                    $userInfo = $userModel->findOne(['id' => $vo['user_id']], 'nickname')['data'];
                    $userOrderService->doReceived($vo['id'], $vo['user_id'], $userInfo['nickname']);
                }
            }

            $page += 1;
        }
        return self::SUCCESS;
    }

}
